package com.runvp.netty.server.handler;


import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.netty.constant.NettyConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class BaseHandle {


    /**
     * 给对应通道发消息
     * @param sn
     * @param resBody
     */
    public boolean sendMsg(String sn, MessageResBody resBody){
        try{
            log.info("本次通知设备SN:{} ",sn);
            //获取目标底座的通道
            Channel tagChannel = NettyConstant.all.get(sn);
            if(null == tagChannel){
                log.warn("sn为【{}】的通道不存在，执行结束",sn);
                return false;
            }
            String addr = tagChannel.remoteAddress().toString();
            log.info("给sn为【"+sn+"】 地址为【"+addr+"】的客户端发送【"+resBody.getType()+"】指令");
            byte[] bytes = SendMsgHandle.buildSendMsg(resBody);
            if(null == bytes){
                log.warn("发送信息为空,执行中断");
                return false;
            }
            ByteBuf buff = Unpooled.buffer();//netty需要用ByteBuf传输
            buff.writeBytes(bytes);//对接需要16进制
            tagChannel.write(buff);
            tagChannel.flush();
            log.info("发送完毕... ");
            return true;
        }catch (Exception e){
            log.error("send msg error :{}",e);
            return false;
        }

    }
}
